import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:shudu/utils/history_model.dart';

class SharePreference {
  static SharePreference? _singleton;
  static SharedPreferences? _prefs;
  static String RECORD = "sp_history";
  static String MUSIC = "sp_music";
  static String VIBRATE = "sp_vibrate";

  static Future<SharePreference> getInstance() async {
    if (_singleton == null) {
      if (_singleton == null) {
        var singleton = SharePreference._();
        await singleton._init();
        _singleton = singleton;
      }
    }
    return _singleton!;
  }

  SharePreference._();

  Future _init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  static List getHistoryRecord() {
    if (_prefs == null) return [];
    String recordStr = _prefs!.getString(RECORD) ?? "[]";
    return json.decode(recordStr);
  }

  static void addHistoryRecord(HistoryModel model) {
    if (_prefs == null) return;
    List records = getHistoryRecord();
    records.insert(0, model);
    _prefs!.setString(RECORD, json.encode(records));
  }

  static void setMusic(bool isPlay) {
    if (_prefs == null) return;
    _prefs!.setBool(MUSIC, isPlay);
  }

  static bool getMusic() {
    if (_prefs == null) return true;
    return _prefs!.getBool(MUSIC) ?? true;
  }

  static void setVibrate(bool isVibrate) {
    if (_prefs == null) return;
    _prefs!.setBool(VIBRATE, isVibrate);
  }

  static bool getVibrate() {
    if (_prefs == null) return true;
    return _prefs!.getBool(VIBRATE) ?? true;
  }
}
